import Taro, { useState, useEffect, setStorage } from "@tarojs/taro";
import { View, Text, Button } from "@tarojs/components";
import { AtButton, AtMessage, AtAvatar } from "taro-ui";
import { getCodeImg } from "../../api/user";
import { setS, getS, delS } from "../../tools/localStroage";
import { Login, getAccountInfo, getUserInfo } from "../../special/userinfo";
const Index = () => {
  useEffect(() => {
    getOauthStatus();
  }, []);

  const [str, setStr] = useState("");
  return (
    <View>
      <AtMessage />
      <AtButton onClick={handleClick}>按钮文案</AtButton>
      <AtButton onClick={handleGetTest}>发送请求</AtButton>
      <AtButton onClick={handleSetLoact}>存进本地缓存</AtButton>
      <AtButton onClick={handleGetLoact}>取出本地缓存</AtButton>
      <AtButton onClick={handleDelLoact}>删除本地缓存</AtButton>
      <AtButton onClick={handleLogin}>登录</AtButton>
      <AtButton onClick={handleAccountInfo}>获取账户信息</AtButton>
      <Button openType="getUserInfo" onGetUserInfo={onGotUserInfo}>
        获取用户信息
      </Button>
      <Button onClick={getOauthStatus}>获取用户授权结果</Button>
      <AtAvatar image={str}></AtAvatar>
    </View>
  );
  function handleClick() {
    Taro.atMessage({
      message: "消息通知",
      type: "success",
    });
  }

  function handleGetTest() {
    this.deviceId = new Date().getTime();
    getCodeImg({
      deviceId: this.deviceId,
    })
      .then((res) => {
        setStr("data:image/jpg;base64," + res.result);
      })
      .catch((err) => {});
  }

  function handleSetLoact() {
    setS("abc", { a: "xx" }, (res) => {
      console.log("存入成功", res);
    });
  }

  function handleGetLoact() {
    getS("abc", (res) => {
      console.log("取出: ", res);
    });
  }

  function handleDelLoact() {
    delS("abc", (res) => {
      console.log("删除: ", res);
    });
  }

  function handleLogin() {
    Login();
  }

  function handleAccountInfo() {
    const [appid] = getAccountInfo();
    console.log("appid: ", appid);
  }

  function onGotUserInfo(res) {
    if (res.detail.userInfo) {
      // 返回的信息中包含用户信息则证明用户允许获取信息授权
      console.log("res.detail.userInfo: ", res.detail.userInfo);
      console.log("授权成功");
    } else {
      // 用户取消授权，进行提示，促进重新授权
      Taro.showModal({
        title: "温馨提示",
        content: "简单的信任，是你我俩故事的开始",
        showCancel: false, // 不展示取消按钮
      });
    }
  }

  // 获取用户授权结果
  function getOauthStatus() {
    Taro.getSetting()
      .then((res) => {
        console.log(res);
        if (
          Object.keys(res.authSetting).length === 0 ||
          !res.authSetting["scope.userInfo"]
        ) {
          // 用户信息无授权
          console.log(res.authSetting);
          console.log("用户无授权信息");
        } else {
          // 用户允许授权获取用户信息
          // 隐藏授权按钮
          this.setState({ oauthBtnStatus: false });
          // 获取用户信息
          this.getUserInfo();
        }
      })
      .catch((err) => console.log(err));
  }
};

Index.config = {
  navigationBarTitleText: "西乡",
};

export default Index;
